package org.nimi317.web_gis.service.impl;


import cn.hutool.core.util.DesensitizedUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.nimi317.web_gis.Enum.Role;
import org.nimi317.web_gis.Enum.UserStatus;
import org.nimi317.web_gis.dao.UserMapper;
import org.nimi317.web_gis.entity.UR;
import org.nimi317.web_gis.entity.User;
import org.nimi317.web_gis.service.IURService;
import org.nimi317.web_gis.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author nimi317
 * @since 2024-04-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final IURService iurService;

    private final UserMapper userMapper;

    public UserServiceImpl(IURService iurService, UserMapper userMapper) {
        this.iurService = iurService;
        this.userMapper = userMapper;
    }

    @Override
    public boolean existByEmail(String email) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, email);
        return this.exists(wrapper);
    }

    @Override
    public User getByEmail(String email) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, email);
        return this.getOne(wrapper);
    }

    @Override
    @Transactional
    public User createByEmail(String email, String uName) {
        User entity = new User();
        entity.setEmail(email);
        entity.setUserName(uName);
        entity.setStatus(UserStatus.NORMAL);
        this.save(entity);

        iurService.save(new UR(entity.getId(), Role.COMMON.getCode()));
        return this.getByEmail(email);
    }

    @Override
    public Page<User> pageUser(org.nimi317.web_gis.form.post.Page page) {
        //脱敏
        Page<User> userPage = userMapper.pageUsers(null);
        userPage.setRecords(userPage.getRecords().stream().peek(item-> item.setEmail(DesensitizedUtil.email(item.getEmail()))).toList());
        return userPage;
    }
}
